#include "file_loader.h"
#include <QFile>
#include <QTextStream>

FileLoader::FileLoader(QString path)
{
    _path = path;
}


bool FileLoader::loadIndividuals(int numStrata, int numSpatial, int numExternal, int numLoci, GENOTYPE_INPUT_FORMAT format) {

    QFile data( _path );
    if( data.open( QFile::ReadOnly | QFile::Text ) ) {
        QTextStream in(&data);
        QStringList header =  in.readLine().split( ",", QString::SkipEmptyParts );
        QStringList line;

        /*
        if( header.length() > (numStrata + numSpatial + numExternal + numLoci ) ) {
            printf( "ERROR: Header wrong length Header=%d total=%d\n", header.length(), (numStrata + numSpatial + numExternal + numLoci ) );
            return false;
        }
        */

        while(  !(line = in.readLine().split(",",QString::SkipEmptyParts) ).isEmpty() ) {

            if( header.count() == line.count() || header.count() == (line.count() + numLoci) ){
                Individual *theInd = new Individual();
                int idx=0;
                qreal val;
                bool ok;

                for(int i=0;i<numStrata;i++) {
                    theInd->setStrata( header[idx], line[idx] );
                    idx++;
                }

                for(int i=0;i<numSpatial;i++) {
                    val = line[idx].toDouble( &ok );
                    if( ok )
                        theInd->setSpatial(header[idx], val );
                    idx++;
                }

                for(int i=0;i<numExternal;i++) {
                    val = line[idx].toDouble( &ok );
                    if( ok )
                        theInd->setExternal( header[idx], val );
                    idx++;
                }
                int hdr = idx;
                for(int i=0;i<numLoci;i++) {
                    QStringList geno;

                    if( format == GENOS_DIPLOID_TWO_COLUMN ){
                        geno << line[idx];
                        geno << line[idx+1];
                        idx++;
                    }

                    else if( format == GENOS_DIPLOID_ONE_COLUMN ) {
                        QString wholeGeno = line[idx];
                        int numAlleles = wholeGeno.length() / 2;
                        geno << wholeGeno.left(numAlleles);
                        geno << wholeGeno.right(numAlleles);
                    }

                    else if( format == GENOS_HAPLOID )
                        geno << line[idx];

                    else if( format == GENOS_TETRAPLOID )
                        geno << line[idx].split(":");

                    geno.sort();
                    theInd->setLocus( header[hdr], new Locus( geno.join(":")) );
                    idx++; hdr++;
                }

                if( theInd->count() )
                    _individuals.append( theInd );
            }

        }
        data.close();
        return _individuals.count() > 0;
    }
    else
        return false;
}
